Solving Pattern Printing and Loop-Based Programming Problems in Core Java
Course: Core Java Training
Topic: Solving Pattern Printing and Loop-Based Programming Problems
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Pattern Printing and Loop-Based Problems
Pattern printing and loop-based programming problems are important exercises in Core Java. They help beginners understand how loops, conditional statements, nested iterations, variables, and mathematical operations work together to solve programming challenges.
Pattern printing involves displaying characters, numbers, or symbols in a particular arrangement. Loop-based problems also include calculations such as finding factorials, reversing numbers, checking prime numbers, generating multiplication tables, and calculating digit sums.
These exercises develop logical thinking and are frequently used in beginner programming assessments, coding practice, and technical interviews.
2. Learning Objectives
- Understand the logic behind pattern printing problems.
- Use
for, while, and do-while loops effectively.
- Apply nested loops to create rows and columns.
- Print star, number, and character patterns.
- Solve mathematical problems using loops.
- Use conditions inside loops to control program execution.
- Trace program execution and identify logical errors.
- Improve problem-solving skills through practice exercises.
3. Understanding Loops in Java
A loop executes a block of code repeatedly while a specified condition is satisfied or until a defined stopping point is reached.
3.1 The for Loop
The for loop is useful when the number of iterations is known in advance.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
3.2 The while Loop
The while loop checks its condition before executing the loop body. It is useful when the number of repetitions depends on a condition.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
3.3 The do-while Loop
The do-while loop executes its body at least once because the condition is evaluated after the loop body.
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
3.4 Comparison of Java Loops
| Loop |
Condition Checked |
Best Use Case |
for |
Before each iteration |
Known iteration count and index-based patterns |
while |
Before each iteration |
Repeating until a condition changes |
do-while |
After each iteration |
At least one execution is required |
4. Understanding Pattern Printing Logic
Most basic patterns are constructed using nested loops. The outer loop controls the rows, while the inner loop controls what is printed within each row.
- Outer loop: Determines the current row.
- Inner loop: Prints the characters, numbers, or spaces for that row.
- Print statement: Displays each item without moving to the next line.
- println statement: Moves to the next line after a row is completed.
For example, a square pattern with three rows and three columns requires an outer loop that runs three times and an inner loop that runs three times for each row.
5. Printing a Square Star Pattern
A square star pattern displays the same number of stars in every row.
Expected output:
* * *
* * *
* * *
Java program:
public class SquarePattern {
public static void main(String[] args) {
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Explanation: The outer loop runs three times. For each row, the inner loop prints three stars. After the inner loop finishes, System.out.println() moves the cursor to the next line.
6. Printing a Right-Angled Triangle
In a right-angled triangle, the number of stars increases by one in each successive row.
Expected output:
*
* *
* * *
* * * *
Java program:
public class RightTriangle {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
How it works:
- Row 1 prints one star.
- Row 2 prints two stars.
- Row 3 prints three stars.
- Row 4 prints four stars.
The inner loop uses j <= i, so its iteration count changes according to the current row number.
7. Printing an Inverted Triangle
An inverted triangle starts with the maximum number of stars and decreases the number in each row.
Expected output:
* * * *
* * *
* *
*
Java program:
public class InvertedTriangle {
public static void main(String[] args) {
int n = 4;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Explanation: The outer loop counts downward from n to 1. The inner loop prints as many stars as the current value of i.
8. Printing a Pyramid Pattern
A pyramid uses spaces before the stars to align each row around the center.
Expected output:
*
* *
* * *
* * * *
Java program:
public class PyramidPattern {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int space = 1; space <= n - i; space++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Explanation: The first inner loop prints leading spaces, and the second inner loop prints stars. As the row number increases, the number of leading spaces decreases.
Important: Exact visual alignment depends on the width of the characters and spaces used. For more precise console alignment, use consistent spacing.
9. Printing a Number Triangle
Number patterns use integers instead of symbols. In this example, each row prints the numbers from 1 up to the current row number.
Expected output:
1
1 2
1 2 3
1 2 3 4
Java program:
public class NumberTriangle {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Here, the inner loop variable j is printed instead of printing a fixed symbol. This allows the output to change with every iteration.
10. Printing Repeated-Number Patterns
A repeated-number pattern prints the current row number multiple times.
Expected output:
1
2 2
3 3 3
4 4 4 4
Java program:
public class RepeatedNumberPattern {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
The key difference from the previous example is that the program prints i instead of j. The outer loop controls the repeated value.
11. Printing an Alphabet Pattern
Java supports character arithmetic. Incrementing a character such as 'A' produces the next character in the basic Latin alphabet sequence.
Expected output:
A
A B
A B C
A B C D
Java program:
public class AlphabetPattern {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
char ch = (char) ('A' + j);
System.out.print(ch + " ");
}
System.out.println();
}
}
}
Explanation: The expression 'A' + j calculates a character code. Casting the result to char converts it back to a character.
12. Solving Mathematical Problems Using Loops
Loop-based programming extends beyond printing patterns. Loops can process numbers digit by digit, perform repeated calculations, and test mathematical conditions.
12.1 Sum of the First N Natural Numbers
This problem calculates the sum of all integers from 1 to a given positive integer.
public class NaturalNumberSum {
public static void main(String[] args) {
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
}
}
Output: Sum = 55
The variable sum accumulates the value of each number as the loop progresses.
12.2 Factorial of a Number
The factorial of a non-negative integer is the product of all positive integers up to that number. By definition, 0! = 1.
public class FactorialExample {
public static void main(String[] args) {
int n = 5;
long factorial = 1;
if (n < 0) {
System.out.println("Factorial is not defined for negative integers.");
return;
}
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial = " + factorial);
}
}
Output: Factorial = 120
Using long provides a larger range than int, but even long overflows for sufficiently large factorials. Validate input limits when developing a reusable solution.
12.3 Multiplication Table
A multiplication table can be generated by multiplying a fixed number by each integer in a chosen range.
public class MultiplicationTable {
public static void main(String[] args) {
int number = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}
This example prints the multiplication table of 7 from 1 to 10.
12.4 Reverse a Number
Reversing a number involves repeatedly extracting its last digit and adding that digit to a new number.
public class ReverseNumber {
public static void main(String[] args) {
int number = 1234;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
System.out.println("Reversed number = " + reversed);
}
}
Output: Reversed number = 4321
The modulo operator % extracts the last digit, while integer division by 10 removes that digit. This basic example assumes a non-negative input and a result that fits within the int range.
12.5 Sum of Digits
public class SumOfDigits {
public static void main(String[] args) {
int number = 582;
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
System.out.println("Digit sum = " + sum);
}
}
Output: Digit sum = 15
For the number 582, the digits are 5, 8, and 2. Their sum is 15. For a reusable method, consider handling negative values and zero explicitly.
12.6 Check Whether a Number Is Prime
A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.
public class PrimeNumber {
public static void main(String[] args) {
int number = 17;
boolean isPrime = number > 1;
for (int i = 2; i <= number / i && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
if (isPrime) {
System.out.println(number + " is prime.");
} else {
System.out.println(number + " is not prime.");
}
}
}
Output: 17 is prime.
The loop tests possible divisors only up to the square root of the number. The condition i <= number / i avoids multiplication overflow that could occur with i * i for very large integers.
13. Using Conditional Statements Inside Loops
Conditions allow programs to make decisions during repeated execution. The if, else if, and else statements are often used with loops to print selected values or process numbers according to a rule.
Example: Print even numbers from 1 to 20.
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}
Output: 2 4 6 8 10 12 14 16 18 20
The condition i % 2 == 0 checks whether the number is divisible by 2 without a remainder.
14. Using break and continue
14.1 The break Statement
The break statement immediately exits the nearest enclosing loop.
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
System.out.print(i + " ");
}
}
}
Output: 1 2 3 4 5
14.2 The continue Statement
The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.print(i + " ");
}
}
}
Output: 1 3 5 7 9
15. A Step-by-Step Method for Solving Pattern Problems
- Study the required output: Identify how many rows and columns appear.
- Determine the row rule: Find out how the number of items changes from one row to the next.
- Choose the outer loop: Use it to control the number of rows.
- Design the inner loop: Decide how many symbols, numbers, or spaces to print for each row.
- Identify changing values: Decide whether to print the row index, column index, a character, or a calculated value.
- Add conditions if necessary: Use conditional statements for alternate, hollow, or selective patterns.
- Trace the first few iterations: Verify the output row by row before running the entire program.
- Test different inputs: Check the program with small values, typical values, and invalid values where applicable.
16. Dry Running a Nested Loop
Dry running means manually tracing a program to understand how its variables change during execution.
Consider the following code:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Iteration trace:
| Outer Loop (i) |
Inner Loop Values (j) |
Output Row |
| 1 |
1 |
1 |
| 2 |
1, 2 |
1 2 |
| 3 |
1, 2, 3 |
1 2 3 |
Dry running makes it easier to identify incorrect loop conditions, missing increments, and unexpected output.
17. Common Mistakes and Troubleshooting
| Mistake |
Why It Happens |
Solution |
| Infinite loop |
The loop variable does not move toward the stopping condition. |
Check the increment, decrement, and condition. |
| Incorrect number of rows |
The outer loop uses the wrong starting or ending value. |
Verify the row count and boundary conditions. |
| Incorrect number of symbols |
The inner loop condition does not match the pattern rule. |
Trace the inner loop for each row. |
| Unexpected spaces |
Leading spaces or separators are printed incorrectly. |
Separate the spacing logic from the symbol logic. |
| Wrong number in a pattern |
The program prints the wrong loop variable. |
Check whether the pattern needs the row index or column index. |
| Incorrect factorial result |
The accumulator starts at zero instead of one. |
Initialize the product accumulator to 1. |
| Incorrect digit calculation |
Modulo and integer division are used incorrectly. |
Use % 10 to extract the last digit and /= 10 to remove it. |
| Integer overflow |
A calculation exceeds the numeric type's range. |
Choose an appropriate type and validate limits. |
18. Best Practices for Loop-Based Programming
- Use meaningful variable names when the logic becomes complex.
- Keep loop conditions simple and easy to understand.
- Initialize counters and accumulators correctly.
- Use nested loops only when the problem requires repeated work within each iteration.
- Avoid unnecessary calculations inside loops.
- Validate user input when accepting values from a console or application.
- Test edge cases such as zero, one, negative values, and large numbers where relevant.
- Use comments to explain non-obvious logic rather than every statement.
- Separate reusable logic into methods when a program grows.
- Check execution time when processing large inputs or deeply nested loops.
19. Understanding Time Complexity
Time complexity describes how the amount of work performed by an algorithm grows as the input size increases.
| Loop Structure |
Typical Complexity |
Example |
| One loop from 1 to n |
O(n) |
Sum of natural numbers |
| Two independent nested loops, each running n times |
O(n²) |
Printing an n-by-n square |
| Nested triangle loops with row lengths from 1 to n |
O(n²) |
Printing a right-angled triangle |
| Repeatedly divide a positive number by 10 |
O(log n) |
Processing decimal digits |
These are typical classifications. The actual complexity depends on the loop bounds and operations performed. For example, a square pattern with n rows and n columns prints n² symbols, so the output itself requires quadratic work.
20. Practice Exercises
Try solving the following problems without looking at a completed solution first.
Beginner Level
- Print numbers from 1 to 100.
- Print all odd numbers between 1 and 50.
- Generate the multiplication table of a user-provided number.
- Calculate the sum of the first n natural numbers.
- Print a square star pattern of size n.
- Print a right-angled triangle using stars.
Intermediate Level
- Print an inverted star triangle.
- Print a pyramid using stars and spaces.
- Print a number triangle where each row begins at 1.
- Print a repeated-number triangle.
- Calculate the factorial of a non-negative integer.
- Reverse a number and calculate its digit sum.
- Check whether a number is prime.
Advanced Beginner Challenges
- Print a hollow square using stars.
- Print a diamond pattern using nested loops.
- Print a number pyramid with increasing and decreasing values.
- Check whether a number is a palindrome.
- Generate the Fibonacci sequence for n terms.
- Print all prime numbers within a given range.
- Count the number of digits in a positive integer.
21. Mini Project: Pattern and Number Practice Menu
Create a console application that allows users to choose a pattern or mathematical operation. This project combines loops, conditional statements, methods, and basic input handling.
Suggested features:
- Display a menu with options for a star triangle, number triangle, factorial, digit sum, and multiplication table.
- Accept a menu choice and required input from the user.
- Use a
switch statement to select the operation.
- Implement each operation in a separate method.
- Use a loop to display the menu again until the user chooses to exit.
- Handle invalid choices and invalid numeric inputs appropriately.
Sample menu:
1. Print Star Triangle
2. Print Number Triangle
3. Calculate Factorial
4. Calculate Digit Sum
5. Print Multiplication Table
0. Exit
Enter your choice:
Project learning outcome: This project demonstrates how loop logic can be organized into a small, reusable Java application rather than isolated code examples.
22. Interview Questions and Answers
Q1. What is pattern printing in Java?
Answer: Pattern printing is the process of displaying symbols, numbers, or characters in a structured arrangement using loops and, when required, conditional statements.
Q2. Why are nested loops used for patterns?
Answer: Nested loops allow one loop to control rows while another controls the items printed within each row.
Q3. What is the difference between print() and println()?
Answer: print() displays content without automatically moving to a new line. println() displays content and then moves to a new line.
Q4. How can you print a triangle with increasing stars?
Answer: Use an outer loop for the rows and an inner loop whose upper bound is the current row number.
Q5. How can you print an inverted triangle?
Answer: Start the outer loop at the maximum row count and decrease the number of symbols printed in each successive row.
Q6. What causes an infinite loop?
Answer: An infinite loop occurs when the termination condition never becomes false, often because a counter is not updated correctly.
Q7. How do you calculate factorial using a loop?
Answer: Initialize a product variable to 1 and multiply it by each integer from 1 through n. Handle negative inputs separately.
Q8. How do you reverse a number using a loop?
Answer: Extract the last digit using modulo 10, append it to a result multiplied by 10, and remove the digit using integer division by 10.
Q9. What is the time complexity of two nested loops that each run n times?
Answer: The time complexity is typically O(n²), because the inner loop executes n times for each of the n outer-loop iterations.
Q10. How do you debug an incorrect pattern?
Answer: Verify the row and column counts, check the loop boundaries, inspect spacing logic, and manually trace a few iterations.
23. Quick Revision Checklist
- Understand the difference between
for, while, and do-while loops.
- Remember that nested loops are commonly used for row-and-column patterns.
- Use
System.out.print() for items on the same line and System.out.println() to move to the next line.
- Determine whether the current pattern needs the row index or column index.
- Use spaces carefully to align pyramids and other centered patterns.
- Practice factorial, digit sum, number reversal, prime checking, and multiplication tables.
- Dry run the code to detect logic errors.
- Check edge cases and numeric limits.
- Understand basic time complexity for single and nested loops.
- Practice writing complete Java programs independently.
24. Conclusion
Solving pattern printing and loop-based programming problems builds a strong foundation in Core Java. These exercises teach how to control repetition, organize nested loops, work with numbers and characters, and combine loops with conditional statements.
Consistent practice is the best way to improve. Start with simple square and triangle patterns, progress to number and alphabet patterns, and then solve mathematical problems such as factorials, prime numbers, and digit operations. Once these concepts become comfortable, combine them into small menu-driven Java projects.
To explore structured Core Java learning, visit JustAcademy's Core Java Training Course. You can also register for a course demo or visit the JustAcademy website.